using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CHEnhanceEfCore.Common;
using CHEnhanceEfCore.Config.Log;
using CHEnhanceEfCore.Models;
using CHEnhanceEfCore.Service;
using Microsoft.AspNetCore.Mvc;

namespace CHEnhanceEfCore.Controller
{
    /// <summary>
    /// author: chenhao
    /// </summary>
    public class UserTaskController : BaseApiController
    {
        private readonly LogUtils _logUtils;
        private readonly IUserTaskService _userTaskService;
        private static readonly SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); // 初始信号量为1，最大信号量也为1

        public UserTaskController(LogUtils logUtils, IUserTaskService userTaskService)
        {
            this._logUtils = logUtils;
            _userTaskService = userTaskService;
        }

        [HttpPost("add")]
        public async Task<Result> add(UserTask userTask)
        {
            await semaphore.WaitAsync();
            try
            {
                UserTask addUserTask = await _userTaskService.addAsync(userTask);
                return null != addUserTask ? Result.success(userTask) : Result.fail("add failure");
            }
            finally
            {
                semaphore.Release(); // 释放信号量
            }
        }

        [HttpPost("deleted")]
        public async Task<Result> deletedAsync(List<Guid> userTaskIdList)
        {
            return await _userTaskService.deletedAsync(userTaskIdList) ? Result.success() : Result.fail("deleted failure");
        }

        [HttpGet("list")]
        public async Task<Result> list()
        {
            return Result.success(data: await _userTaskService.getUserTaskListAsync());
        }

        [HttpGet("generate-uuid")]
        public async Task<Result> generateUUID()
        {
            return Result.success(await _userTaskService.generateUserTaskAsync());
        }
    }
}